﻿using System;
namespace ORS.OrderRobot
{
	public static class CronHelper
	{
        public static string GetCronByInterval(int interval, TimeUnit unit)
        {
            if (interval < 1)
                throw new NotSupportedException("interval 不能小于 1");
            switch (unit)
            {
                case TimeUnit.Second:
                    if (interval < 60)
                    {
                        return "0 * * * * *"; // 每分钟执行一次
                    }
                    else
                    {
                        int minutes = interval / 60;
                        int remainSeconds = interval % 60;

                        if (minutes < 60 && remainSeconds == 0)
                            return $"0 */{minutes} * * * *";
                        else
                        {
                            minutes += remainSeconds > 0 ? 1 : 0;
                            if (minutes < 60)
                                return $"0 */{minutes} * * * *";
                            else
                                return GetCronByInterval(minutes, TimeUnit.Minute);
                        }
                    }

                case TimeUnit.Minute:
                    if (interval < 60)
                        return $"0 */{interval} * * * *";
                    else
                    {
                        int hours = interval / 60;
                        int remainMinutes = interval % 60;

                        if (hours < 24 && remainMinutes == 0)
                            return $"0 0 */{hours} * * *";
                        else
                        {
                            hours += remainMinutes > 0 ? 1 : 0;
                            if (hours < 24)
                                return $"0 0 */{hours} * * *";
                            else
                                return GetCronByInterval(hours, TimeUnit.Hour);
                        }
                    }

                case TimeUnit.Hour:
                    if (interval < 24)
                        return $"0 0 */{interval} * * *";
                    else
                    {
                        int days = interval / 24;
                        int remainHours = interval % 24;
                        days += remainHours > 0 ? 1 : 0;
                        return $"0 0 0 */{days} * *";
                    }

                case TimeUnit.Day:
                    return $"0 0 0 */{interval} * *";
                default:
                    throw new NotSupportedException("不支持的单位：" + unit);
            }
        }

    }
}

